package mygroup.test.hadooptest;

import java.io.IOException;
import java.nio.file.Paths;
import java.util.Iterator;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class MyReduce extends Reducer<Text, IntWritable, Text, IntWritable> {

	private IntWritable totalNum = new IntWritable();

	@Override
	protected void reduce(Text key, Iterable<IntWritable> values,
			Context context) throws IOException, InterruptedException {
		int sum = 0;
		Iterator<IntWritable> it = values.iterator();
		while (it.hasNext()) {
			sum += it.next().get();
		}
		totalNum.set(sum);
		context.write(key, totalNum);
	}

	public static void main(String[] args) throws Exception {
		Configuration conf = new Configuration();

		Job job = new Job(conf, "MyWordCount");

		job.setJarByClass(MyReduce.class); 

		job.setMapperClass(MyMap.class);
		job.setReducerClass(MyReduce.class);
		job.setCombinerClass(MyReduce.class);

		job.setOutputKeyClass(Text.class); 
		job.setOutputValueClass(IntWritable.class);

		FileInputFormat.addInputPath(job, new Path(args[0]));
		FileOutputFormat.setOutputPath(job, new Path(args[1]));

		System.exit(job.waitForCompletion(true) ? 0 : 1);
	}

}
